﻿using UnityEngine;
using System.Collections;

public class flappingChomper : MonoBehaviour {
	
	public Transform leftFlap;
	public Transform rightFlap;
	public bool isFlapping;
	int flapCounter;
	
	float L_CRot;
	float R_CRot;
	float L_ORot;
	float R_ORot;
	
	bool isOpening;
	float lerp_t = 0;
	public float flapSpeed = 0.5f;
	float initialFlapSpeed;
	public int flapAmount = 10;
	float speedMultiplier = 1.05f;
	
	// Use this for initialization
	void Start () {
		L_CRot = leftFlap.transform.eulerAngles.z;
		R_CRot = rightFlap.transform.eulerAngles.z;
		L_ORot = L_CRot + 45;
		R_ORot = R_CRot - 45;
		initialFlapSpeed = flapSpeed;
	}
	
	// Update is called once per frame
	void Update () {
		if(isFlapping)
		{
			lerp_t += flapSpeed * Time.deltaTime;
			if(lerp_t >= 1)
			{
				lerp_t = 0;
				flapCounter ++;
				isOpening = !isOpening;
				flapSpeed *= speedMultiplier;
				if(flapCounter >= flapAmount)
					isFlapping = false;
			}
			
			Vector3 tmpRot = leftFlap.transform.eulerAngles;
			
			if(isOpening)
				tmpRot.z = Mathf.Lerp(L_CRot,L_ORot,lerp_t);
			else
				tmpRot.z = Mathf.Lerp(L_ORot,L_CRot,lerp_t);
			
			leftFlap.transform.eulerAngles = tmpRot;
			
			tmpRot = rightFlap.transform.eulerAngles;
			
			if(isOpening)
				tmpRot.z = Mathf.Lerp(R_CRot,R_ORot,lerp_t);
			else
				tmpRot.z = Mathf.Lerp(R_ORot,R_CRot,lerp_t);
			
			rightFlap.transform.eulerAngles = tmpRot;
		}
		
		
	}
	
	public void doFlap()
	{
		flapSpeed = initialFlapSpeed;
		isFlapping = true;
		flapCounter = 0;
		lerp_t = 0;
		isOpening = true;
	}
}
